/**
 * 统一的邮件编辑组件 - 支持不同类型的编辑器
 */
import React, { useRef } from 'react';
import { Form, Input, Space, message, Select } from 'antd';
import TinyMCEEditor from '@/components/TinyMCEEditor';
import { TemplateType } from '@/services/emailTemplate';

const { TextArea } = Input;
const { Option } = Select;

interface EmailEditorProps {
  form: any;
  showSubject?: boolean;
  subjectLabel?: string;
  contentLabel?: string;
  subjectPlaceholder?: string;
  contentPlaceholder?: string;
  contentRows?: number;
  templateType?: TemplateType;
  showTemplateType?: boolean;
  onTemplateTypeChange?: (type: TemplateType) => void;
}

// 插入变量到光标位置的工具函数
export const insertVariableAtCursor = (form: any, variableName: string) => {
  const variableText = `{{${variableName}}}`;

  // 获取当前焦点的输入框
  const activeElement = document.activeElement as HTMLInputElement | HTMLTextAreaElement;

  if (activeElement && (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA')) {
    const start = activeElement.selectionStart || 0;
    const end = activeElement.selectionEnd || 0;
    const value = activeElement.value || '';

    // 构造新的值
    const newValue = value.substring(0, start) + variableText + value.substring(end);

    // 确定是哪个字段并更新表单值
    const fieldName = activeElement.getAttribute('id');
    if (fieldName?.includes('subject')) {
      form.setFieldValue('subject', newValue);
      // 设置光标位置
      setTimeout(() => {
        const newPosition = start + variableText.length;
        activeElement.setSelectionRange(newPosition, newPosition);
        activeElement.focus();
      }, 0);
    } else if (fieldName?.includes('content')) {
      form.setFieldValue('content', newValue);
      // 设置光标位置
      setTimeout(() => {
        const newPosition = start + variableText.length;
        activeElement.setSelectionRange(newPosition, newPosition);
        activeElement.focus();
      }, 0);
    }

    message.success(`已插入变量: ${variableText}`);
  } else {
    // 如果没有焦点，默认插入到内容末尾
    const currentContent = form.getFieldValue('content') || '';
    const newContent = currentContent + variableText;
    form.setFieldValue('content', newContent);
    message.success(`已插入变量: ${variableText}`);
  }
};

const EmailEditor: React.FC<EmailEditorProps> = ({
  form,
  showSubject = true,
  subjectLabel = "邮件主题",
  contentLabel = "邮件内容",
  subjectPlaceholder = "请输入邮件主题，支持变量如：{{current_date}}",
  contentPlaceholder = "请输入邮件内容，支持HTML和变量，如：今天是{{current_date}}，祝您工作愉快！",
  contentRows = 15,
  templateType = TemplateType.HTML,
  showTemplateType = false,
  onTemplateTypeChange,
}) => {
  const subjectInputRef = useRef<any>(null);
  const contentInputRef = useRef<any>(null);


  // 根据模板类型渲染不同的编辑器
  const renderContentEditor = () => {
    const currentContent = form.getFieldValue('content') || '';

    switch (templateType) {
      case TemplateType.HTML:
        return (
          <TinyMCEEditor
            value={currentContent}
            onChange={(content) => {
              form.setFieldValue('content', content);
            }}
            height={Math.max(600, contentRows * 30)}
            placeholder={contentPlaceholder}
          />
        );

      case TemplateType.MARKDOWN:
        return (
          <TextArea
            ref={contentInputRef}
            placeholder="请输入Markdown格式的内容，如：# 标题\n\n**粗体文本**\n\n今天是{{current_date}}"
            rows={contentRows}
            style={{ fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace' }}
          />
        );

      case TemplateType.PLAIN_TEXT:
      default:
        return (
          <TextArea
            ref={contentInputRef}
            placeholder={contentPlaceholder}
            rows={contentRows}
            style={{ fontFamily: 'monospace' }}
          />
        );
    }
  };

  return (
    <Space direction="vertical" style={{ width: '100%' }} size="middle">
      {/* 模板类型选择 */}
      {showTemplateType && (
        <Form.Item
          name="template_type"
          label="模板类型"
          rules={[{ required: true, message: '请选择模板类型' }]}
        >
          <Select
            placeholder="选择模板类型"
            onChange={onTemplateTypeChange}
            style={{ width: '200px' }}
          >
            <Option value={TemplateType.HTML}>
              <Space>
                🌐 HTML格式
                <span style={{ color: '#666', fontSize: '12px' }}>支持富文本编辑</span>
              </Space>
            </Option>
            <Option value={TemplateType.MARKDOWN}>
              <Space>
                📝 Markdown格式
                <span style={{ color: '#666', fontSize: '12px' }}>轻量级标记语言</span>
              </Space>
            </Option>
            <Option value={TemplateType.PLAIN_TEXT}>
              <Space>
                📄 纯文本格式
                <span style={{ color: '#666', fontSize: '12px' }}>简单文本内容</span>
              </Space>
            </Option>
          </Select>
        </Form.Item>
      )}

      {/* 邮件主题 */}
      {showSubject && (
        <Form.Item
          name="subject"
          label={subjectLabel}
          rules={[{ required: true, message: `请输入${subjectLabel}` }]}
        >
          <Input
            ref={subjectInputRef}
            placeholder={subjectPlaceholder}
            size="large"
          />
        </Form.Item>
      )}

      {/* 邮件内容 */}
      <Form.Item
        name="content"
        label={contentLabel}
        rules={[{ required: true, message: `请输入${contentLabel}` }]}
      >
        {renderContentEditor()}
      </Form.Item>
    </Space>
  );
};

export default EmailEditor;
